<?php

namespace app\admin\controller;

use think\Loader;
use think\Request;
use app\common\controller\Base;
use app\common\model\Shop as ShopModel;
use app\common\model\ShopCat as ShopCatModel;
use app\common\tool\Tool;

class Shop extends Base
{
    public function index(){
        $shops = ShopModel::order('id desc')->paginate(20);

        return view('',['shops'=>$shops]);
    }

    public function add(){
        $shopCat = ShopCatModel::all();
        $shopCat = collection($shopCat)->toArray();

        return view('',['shopCat'=>$shopCat]);
    }

    public function edit(Request $request){
        $id = $request->param('id',0,'intval');
        $shop = ShopModel::find($id);
        if(!$shop){
            $this->error("非法渠道访问");
        }
        $shopCat = ShopCatModel::all();
        $shopCat = collection($shopCat)->toArray();

        return view('',['shop'=>$shop,'shopCat'=>$shopCat]);
    }


    public function create(Request $request){
        if(!$request->isPost()){
            $this->error("非法渠道访问");
        }

        $data = $request->only(['name','address','mobile','cover','status','cat']);

        if(isset($data['status']) && $data['status'] == 'on'){
            $data['status'] = 1;
        }else{
            $data['status'] = 0;
        }


        $validate = Loader::validate('ShopValidate');
        $result = $validate->scene('add')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }

        $shopModel = new ShopModel();
        $shopModel->save($data);

        $this->success('操作成功');
    }


    public function update(Request $request){
        if(!$request->isPost()){
            $this->error("非法渠道访问");
        }
        $id = $request->param('id',0,'intval');

        $data = $request->only(['name','address','mobile','cover','status','cat']);

        if(isset($data['status']) && $data['status'] == 'on'){
            $data['status'] = 1;
        }else{
            $data['status'] = 0;
        }


        $validate = Loader::validate('ShopValidate');
        $result = $validate->scene('edit')->check($data);
        if(!$result){
            $this->error($validate->getError());
        }

        $shopModel = ShopModel::find($id);
        $shopModel->save($data);

        $this->success('操作成功');


    }


    public function delete(Request $request){
        if(!$request->isDelete()){
            $this->error("非法渠道访问");
        }
        $id = $request->param('id',0,'intval');
        ShopModel::destroy($id);
        $this->success('操作成功');
    }


}
